<template>
  <div class="candidates-management">
    <!-- 页面头部  使用CommonPageHeader组件-->
    <CommonPageHeader :remark="'管理所有投递简历的候选人信息'" :title="'候选人管理'">
      <template #tool>
        <el-button type="success" @click="handleBatchExport">
          <el-icon>
            <Download />
          </el-icon>
          导出简历
        </el-button>
      </template>
    </CommonPageHeader>


    <!-- 统计卡片  使用StatCard组件-->
    <StatCard :stats="stats"></StatCard>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="候选人姓名">
          <el-input v-model="searchForm.candidateName" placeholder="请输入候选人姓名" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="应聘职位">
          <el-select v-model="searchForm.jobId" placeholder="请选择职位" clearable filterable style="width: 200px">
            <el-option v-for="job in jobList" :key="job.id" :label="job.title" :value="job.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="投递状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="待处理" value="pending" />
            <el-option label="已查看" value="viewed" />
            <el-option label="面试邀请" value="interview_invited" />
            <el-option label="面试中" value="interviewing" />
            <el-option label="面试通过" value="interview_passed" />
            <el-option label="已发Offer" value="offer_sent" />
            <el-option label="已录用" value="hired" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="投递时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 候选人列表 -->
    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="55" />

        <!-- 候选人信息 -->
        <el-table-column label="候选人信息" min-width="200">
          <template #default="{ row }">
            <div class="candidate-info">
              <el-avatar :size="40" :src="row.avatar">
                <el-icon>
                  <User />
                </el-icon>
              </el-avatar>
              <div class="info-content">
                <div class="candidate-name">{{ row.candidateName }}</div>
                <div class="candidate-email">{{ row.email }}</div>
                <div class="candidate-phone">{{ row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 应聘职位 -->
        <el-table-column label="应聘职位" min-width="150">
          <template #default="{ row }">
            <div class="job-info">
              <div class="job-title">{{ row.jobTitle }}</div>
              <div class="job-department">{{ row.department }}</div>
            </div>
          </template>
        </el-table-column>

        <!-- 工作经验 -->
        <el-table-column label="工作经验" width="100">
          <template #default="{ row }">
            {{ row.workExperience }}年
          </template>
        </el-table-column>

        <!-- 期望薪资 -->
        <el-table-column label="期望薪资" width="120">
          <template #default="{ row }">
            {{ row.expectedSalary ? `${row.expectedSalary}K` : '面议' }}
          </template>
        </el-table-column>

        <!-- 投递状态 -->
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 投递时间 -->
        <el-table-column label="投递时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.applyTime) }}
          </template>
        </el-table-column>

        <!-- 匹配度 -->
        <el-table-column label="匹配度" width="100">
          <template #default="{ row }">
            <el-progress :percentage="row.matchScore" :color="getMatchColor(row.matchScore)" :stroke-width="8" />
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewResume(row)">
              <el-icon>
                <Document />
              </el-icon>
              查看简历
            </el-button>
            <el-button type="success" link @click="handleInviteInterview(row)">
              <el-icon>
                <VideoCamera />
              </el-icon>
              邀请面试
            </el-button>
            <el-dropdown @command="(command: string) => handleMoreAction(command, row)">
              <el-button type="primary" link>
                更多
                <el-icon>
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="sendOffer">
                    <el-icon>
                      <Medal />
                    </el-icon>
                    发送Offer
                  </el-dropdown-item>
                  <el-dropdown-item command="reject">
                    <el-icon>
                      <Close />
                    </el-icon>
                    拒绝候选人
                  </el-dropdown-item>
                  <el-dropdown-item command="addNote">
                    <el-icon>
                      <EditPen />
                    </el-icon>
                    添加备注
                  </el-dropdown-item>
                  <el-dropdown-item command="viewHistory">
                    <el-icon>
                      <Clock />
                    </el-icon>
                    查看历史
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedRows.length > 0">
        <span class="selected-info">已选择 {{ selectedRows.length }} 项</span>
        <el-button type="success" @click="handleBatchInvite">
          <el-icon>
            <VideoCamera />
          </el-icon>
          批量邀请面试
        </el-button>
        <el-button type="warning" @click="handleBatchReject">
          <el-icon>
            <Close />
          </el-icon>
          批量拒绝
        </el-button>
        <el-button type="primary" @click="handleBatchExportSelected">
          <el-icon>
            <Download />
          </el-icon>
          导出选中
        </el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 简历详情对话框 -->
    <el-dialog v-model="resumeDialogVisible" title="简历详情" width="80%" top="5vh">
      <div v-if="currentResume" class="resume-detail">
        <!-- 基本信息 -->
        <div class="resume-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <label>姓名：</label>
                <span>{{ currentResume.candidateName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>性别：</label>
                <span>{{ currentResume.gender }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <label>年龄：</label>
                <span>{{ currentResume.age }}岁</span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>邮箱：</label>
                <span>{{ currentResume.email }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>手机：</label>
                <span>{{ currentResume.phone }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 工作经历 -->
        <div class="resume-section">
          <h3>工作经历</h3>
          <div v-for="(exp, index) in currentResume.workExperiences" :key="index" class="experience-item">
            <div class="exp-header">
              <span class="company">{{ exp.company }}</span>
              <span class="position">{{ exp.position }}</span>
              <span class="duration">{{ exp.startDate }} - {{ exp.endDate }}</span>
            </div>
            <div class="exp-description">{{ exp.description }}</div>
          </div>
        </div>

        <!-- 教育背景 -->
        <div class="resume-section">
          <h3>教育背景</h3>
          <div v-for="(edu, index) in currentResume.educations" :key="index" class="education-item">
            <div class="edu-header">
              <span class="school">{{ edu.school }}</span>
              <span class="major">{{ edu.major }}</span>
              <span class="degree">{{ edu.degree }}</span>
              <span class="duration">{{ edu.startDate }} - {{ edu.endDate }}</span>
            </div>
          </div>
        </div>

        <!-- 技能特长 -->
        <div class="resume-section">
          <h3>技能特长</h3>
          <div class="skills">
            <el-tag v-for="skill in currentResume.skills" :key="skill" class="skill-tag">
              {{ skill }}
            </el-tag>
          </div>
        </div>

        <!-- 自我评价 -->
        <div class="resume-section">
          <h3>自我评价</h3>
          <p class="self-evaluation">{{ currentResume.selfEvaluation }}</p>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resumeDialogVisible = false">关闭</el-button>
          <el-button type="success" @click="handleInviteFromResume">
            邀请面试
          </el-button>
          <el-button type="primary" @click="handleSendOfferFromResume">
            发送Offer
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import CommonPageHeader from '@/components/common/PageHeader/CommonPageHeader.vue'
import StatCard from '@/components/stat-card/StatCard.vue'
import { onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Download,
  User,
  Clock,
  VideoCamera,
  Medal,
  Search,
  Refresh,
  Document,
  ArrowDown,
  Close,
  EditPen
} from '@element-plus/icons-vue'
import usePageState from './hooks/usePageState'
import type { CandidateBase } from '@/types'
import type { CurrentResume } from './types'
const {
  loading,
  resumeDialogVisible,
  selectedRows,
  currentResume,
  stats,
  searchForm,
  pagination,
  jobList,
  tableData
} = usePageState()
// 方法定义
/**
 * 获取状态标签类型
 */
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'pending': 'warning',
    'viewed': 'info',
    'interview_invited': 'primary',
    'interviewing': 'primary',
    'interview_passed': 'success',
    'offer_sent': 'success',
    'hired': 'success',
    'rejected': 'danger'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态文本
 */
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'pending': '待处理',
    'viewed': '已查看',
    'interview_invited': '面试邀请',
    'interviewing': '面试中',
    'interview_passed': '面试通过',
    'offer_sent': '已发Offer',
    'hired': '已录用',
    'rejected': '已拒绝'
  }
  return textMap[status] || status
}

/**
 * 获取匹配度颜色
 */
const getMatchColor = (score: number) => {
  if (score >= 80) return '#67c23a'
  if (score >= 60) return '#e6a23c'
  return '#f56c6c'
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    candidateName: '',
    jobId: null,
    status: '',
    dateRange: null
  })
  handleSearch()
}

/**
 * 查看简历
 */
const handleViewResume = (row: CurrentResume) => {
  currentResume.value = row
  resumeDialogVisible.value = true
  // 标记为已查看
  if (row.status === 'pending') {
    row.status = 'viewed'
  }
}

/**
 * 邀请面试
 */
const handleInviteInterview = (row: CurrentResume) => {
  ElMessageBox.confirm(
    `确定要邀请候选人「${row.candidateName}」参加面试吗？`,
    '邀请面试确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    row.status = 'interview_invited'
    ElMessage.success('面试邀请已发送')
    // TODO: 调用API发送面试邀请
  })
}

/**
 * 更多操作
 */
const handleMoreAction = (command: string, row: CandidateBase) => {
  switch (command) {
    case 'sendOffer':
      handleSendOffer(row)
      break
    case 'reject':
      handleRejectCandidate(row)
      break
    case 'addNote':
      handleAddNote(row)
      break
    case 'viewHistory':
      handleViewHistory(row)
      break
  }
}

/**
 * 发送Offer
 */
const handleSendOffer = (row: CurrentResume) => {
  ElMessage.info(`发送Offer给：${row.candidateName}`)
  // TODO: 实现发送Offer功能
}

/**
 * 拒绝候选人
 */
const handleRejectCandidate = (row: CandidateBase) => {
  ElMessageBox.confirm(
    `确定要拒绝候选人「${row.candidateName}」吗？`,
    '拒绝候选人确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.status = 'rejected'
    ElMessage.success('候选人已拒绝')
    // TODO: 调用API拒绝候选人
  })
}

/**
 * 添加备注
 */
const handleAddNote = (row: CandidateBase) => {
  ElMessage.info(`添加备注：${row.candidateName}`)
  // TODO: 实现添加备注功能
}

/**
 * 查看历史
 */
const handleViewHistory = (row: CandidateBase) => {
  ElMessage.info(`查看历史：${row.candidateName}`)
  // TODO: 实现查看历史功能
}

/**
 * 从简历页面邀请面试
 */
const handleInviteFromResume = () => {
  if (currentResume.value) {
    handleInviteInterview(currentResume.value)
    resumeDialogVisible.value = false
  }
}

/**
 * 从简历页面发送Offer
 */
const handleSendOfferFromResume = () => {
  if (currentResume.value) {
    handleSendOffer(currentResume.value)
    resumeDialogVisible.value = false
  }
}

/**
 * 选择改变
 */
const handleSelectionChange = (selection: CandidateBase[]) => {
  selectedRows.value = selection
}

/**
 * 批量邀请面试
 */
const handleBatchInvite = () => {
  ElMessageBox.confirm(
    `确定要邀请选中的 ${selectedRows.value.length} 名候选人参加面试吗？`,
    '批量邀请面试确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    selectedRows.value.forEach((row: CandidateBase) => {
      row.status = 'interview_invited'
    })
    ElMessage.success('批量面试邀请已发送')
    selectedRows.value = []
    // TODO: 调用API批量发送面试邀请
  })
}

/**
 * 批量拒绝
 */
const handleBatchReject = () => {
  ElMessageBox.confirm(
    `确定要拒绝选中的 ${selectedRows.value.length} 名候选人吗？`,
    '批量拒绝确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    selectedRows.value.forEach((row: CandidateBase) => {
      row.status = 'rejected'
    })
    ElMessage.success('批量拒绝成功')
    selectedRows.value = []
    // TODO: 调用API批量拒绝
  })
}

/**
 * 批量导出
 */
const handleBatchExport = () => {
  ElMessage.info('导出所有简历功能开发中')
  // TODO: 实现批量导出功能
}

/**
 * 导出选中
 */
const handleBatchExportSelected = () => {
  ElMessage.info(`导出选中的 ${selectedRows.value.length} 份简历`)
  // TODO: 实现导出选中简历功能
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  loadData()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

/**
 * 加载数据
 */
const loadData = () => {
  loading.value = true
  // TODO: 调用API获取数据
  setTimeout(() => {
    pagination.total = 2
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.candidates-management {
  padding: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
}

.candidate-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-content {
  flex: 1;
}

.candidate-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.candidate-email,
.candidate-phone {
  font-size: 12px;
  color: #909399;
}

.job-info {
  line-height: 1.5;
}

.job-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.job-department {
  font-size: 12px;
  color: #909399;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 12px;
}

.selected-info {
  color: #409eff;
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.resume-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.resume-section {
  margin-bottom: 30px;
}

.resume-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.info-item {
  margin-bottom: 12px;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.experience-item,
.education-item {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 12px;
}

.exp-header,
.edu-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 8px;
}

.company,
.school {
  font-weight: 600;
  color: #303133;
}

.position,
.major {
  color: #409eff;
  font-weight: 500;
}

.duration {
  color: #909399;
  font-size: 14px;
}

.degree {
  color: #67c23a;
  font-weight: 500;
}

.exp-description {
  color: #606266;
  line-height: 1.6;
}

.skills {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.skill-tag {
  margin: 0;
}

.self-evaluation {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .stat-card {
    padding: 16px;
  }

  .stat-number {
    font-size: 20px;
  }

  .exp-header,
  .edu-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
